package com.syg.configuration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author syg
 */
@Configuration
@EnableConfigurationProperties({RequestMappingConfiguration.class})
public class RequestMappingConfiguration {
    Logger log = LoggerFactory.getLogger(RequestMappingConfiguration.class);

    private static final String FLOW_FPI_URL = "zsf.zycfc.modify.headUrl";

    @Bean(name = "flowPropertySourcesPlaceholderConfigurer")
    public PropertySourcesPlaceholderConfigurer modifyPropertySourcesPlaceholderConfigurer(ConfigurableEnvironment environment) {
        PropertySourcesPlaceholderConfigurer configuer = new PropertySourcesPlaceholderConfigurer();
        MutablePropertySources mutablePropertySources = environment.getPropertySources();
        //微服务应用名
        String appName = environment.getProperty("spring.application.name");
        if (StringUtils.isEmpty(appName)) {
            log.warn("未成功替换工作流Fpi路径,原因：未获取到spring.application.name配置属性...");
            configuer.setPropertySources(mutablePropertySources);
            return configuer;
        }
        String[] appNames = appName.split("-");
        //如果服务名以admin结尾
        Map map = new HashMap();
        String baseUrlPrefix = "fpi/" + appNames[0];
        map.put(FLOW_FPI_URL, baseUrlPrefix);
        MapPropertySource mapSource = new MapPropertySource("flowMapSourceName", map);
        mutablePropertySources.addLast(mapSource);
        configuer.setPropertySources(mutablePropertySources);

        log.info("^_^替换工作流Fpi路径成功,FPI访问路径前缀为：{}", baseUrlPrefix);
        return configuer;
    }
}
